package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Slf4j
@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {
    private final UserMapper userMapper;
    private final WeChatProperties weChatProperties;
    private final JwtProperties jwtProperties;
    private final static String JSCODE2SESSION_URL = "https://api.weixin.qq.com/sns/jscode2session";
    @Override
    public UserLoginVO login(String code) {
        HashMap<String, String> params = new HashMap<>();
        params.put("appid", weChatProperties.getAppid());
        params.put("secret", weChatProperties.getSecret());
        params.put("js_code", code);
        params.put("grant_type", "authorization_code");
        String responseJSON = HttpClientUtil.doGet(JSCODE2SESSION_URL, params);
        log.info("校验结果:{}", responseJSON);
        JSONObject jsonObject = JSON.parseObject(responseJSON);
        String openid = jsonObject.getString("openid");
        if (Objects.isNull(openid)){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }

        User user = userMapper.selectByOpenID(openid);
        if (Objects.isNull(user)){
            user = new User();
            user.setOpenid(openid);
            user.setCreateTime(LocalDateTime.now());
            userMapper.InsertUser(user);
        }
        UserLoginVO userLoginVO = new UserLoginVO();
        userLoginVO.setId(user.getId());
        userLoginVO.setOpenid(openid);
        Map<String,Object> map = new HashMap<>();
        map.put("userid",user.getId());

        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), map);
        userLoginVO.setToken(token);
        return userLoginVO;
    }
}
